import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import quarterOfYear from 'dayjs/plugin/quarterOfYear'
import isBetween from 'dayjs/plugin/isBetween'
dayjs.extend(relativeTime)
dayjs.extend(quarterOfYear)
dayjs.extend(isBetween)

import 'dayjs/locale/zh-cn'
dayjs.locale('zh-cn')

// console.log(dayjs())
const filters = {
  /**
   * 功能：将时间戳按照给定的 时间/日期 格式进行处理
   * @param {Number} date 时间戳
   * @param {String} fmt 格式化
   * @returns {String} 规范后的 时间/日期 字符串
   */
  dayjs_formatDate: function (date, fmt = 'YYYY-MM-DD dddd') {
    if (!date) {
      return '';
    }
    return dayjs(date).format(fmt); // 使用 dayjs 格式化时间
  },

  dayjs_fromNow(date, ...args) {
    let obj = dayjs(date);
    let diffed = dayjs().diff(obj, 'hours')
    if (diffed > 11) {
      if (diffed < 24) {
        return '今天 ' + obj.format('HH:mm');
      }
      return obj.format('MM月DD日 HH:mm');
    }
    // return obj.format('YYYY-MM-DD HH:mm');
    return obj.fromNow()
  },
  dayjs_quarterOfYear(date) {
    return dayjs(date).quarter()
  },
  dayjs_isBetween(date, startDate, nextDate, type = 'day', range) {
    return dayjs(date).isBetween(startDate, nextDate, type, range)
  }
}
function installDayjs(Vue) {
  Object.keys(filters).forEach(key => {
    Vue.filter(key, filters[key])
  });
  window.__dayjs_filters__ = {
    ...filters,
    dayjs
  }
}

function installFormart(Vue) {
  let formatUtils = {
    /**
     * 数字转换为万 亿 结束
     * @param num
     * @param point 小数点位数
     * @returns {string}
     */
    tranNumber(num, point){
      // 将数字转换为字符串,然后通过split方法用.分隔,取到第0个
      let numStr = num.toString().split('.')[0]
      if(numStr.length<6) { // 判断数字有多长,如果小于6,,表示10万以内的数字,让其直接显示
        console.log(numStr);
        return numStr;
      }else if(numStr.length>=6 && numStr.length<=8){ // 如果数字大于6位,小于8位,让其数字后面加单位万
        let decimal = numStr.substring(numStr.length-4, numStr.length-4+point)
        console.log(decimal);
        // 由千位,百位组成的一个数字
        return parseFloat(parseInt(num / 10000)+'.'+decimal)+'万'
      }else if(numStr.length >8){ // 如果数字大于8位,让其数字后面加单位亿
        let decimal = numStr.substring(numStr.length-8, numStr.length-8+point);
        console.log(decimal);
        return parseFloat(parseInt(num/100000000)+'.'+decimal)+'亿'
      }
    }
  }

  Object.keys(formatUtils).forEach(key => {
    // console.log(key)
    Vue.filter(key, formatUtils[key])
  });
}


import clickOutSideDirective from './clickOutSide'

export function installDirectives(Vue) {
  installDayjs(Vue);
  installFormart(Vue);
  Vue.directive('click-outside', clickOutSideDirective)

  Vue.filter('z_u_truncate', function (text, stop, clamp) {
    return text.slice(0, stop) + (stop < text.length ? clamp || '...' : '')
  })


  const CLS = 'batch-selecting';
  Vue.directive('batch-select', {
    // 当被绑定的元素插入到 DOM 中时……
    inserted: (el, binding) => {
      // 设置被绑定元素el（即上述的box）的position为relative，目的是让蓝色半透明遮罩area相对其定位
      const relSelName = binding.value.relSelector
      if (relSelName) {
        el.querySelector(relSelName).style.position = 'relative';
      } else {
        el.style.position = 'relative';
      }
      // console.log(el)
      // 记录el在视窗中的位置elPos
      const { x, y } = el.getBoundingClientRect()
      const elPos = { x, y }
      // 获取该指令调用者传递过来的参数：className
      // v-batch-select="{ className: '.el-checkbox', selectIdxs }"
      // 表示要使用鼠标框选类名为'.el-checkbox'的元素
      const optionClassName = binding.value.selector
      let options = []
      // 获取被框选对象们的x、y、width、height
      let optionsXYWH = []

      const getScrollY = binding.value.getScrollY

      // 创建一个div作为area区域，注意定位是absolute，visibility初始值是hidden
      const area = document.createElement('div')
      area.style = 'position: absolute; border: 1px solid #409eff; background-color: rgba(64, 158, 255, 0.1); z-index: 10; visibility: hidden;'
      area.className = 'area'
      area.innerHTML = ''
      el.appendChild(area)
      el.onmousedown = (e) => {
        // console.dir(el)
        if (!e.shiftKey) {
          return;
        }
        el.classList.add(CLS)
        options = [].slice.call(el.querySelectorAll(optionClassName))
        options.forEach(v => {
          const obj = v.getBoundingClientRect()
          optionsXYWH.push({
            x: obj.x - elPos.x,
            y: obj.y - elPos.y + getScrollY(),
            w: obj.width,
            h: obj.height,
            obj: v
          })
        })
        // console.log(optionsXYWH)
        // 获取鼠标按下时相对box的坐标
        const startX = e.clientX - elPos.x
        const startY = e.clientY - elPos.y + getScrollY()
        // 判断鼠标按下后是否发生移动的标识
        let hasMove = false
        document.onmousemove = (e) => {
          hasMove = true
          // 显示area
          area.style.visibility = 'visible'
          // 获取鼠标移动过程中指针的实时位置
          const endX = e.clientX - elPos.x
          const endY = e.clientY - elPos.y  + getScrollY()
          // 这里使用绝对值是为了兼容鼠标从各个方向框选的情况
          const width = Math.abs(endX - startX)
          const height = Math.abs(endY - startY)
          // 根据初始位置和实时位置计算出area的left、top、width、height
          const left = Math.min(startX, endX)
          const top = Math.min(startY, endY)
          // 实时绘制
          area.style.left = `${left}px`
          area.style.top = `${top}px`
          area.style.width = `${width}px`
          area.style.height = `${height}px`
        }
        document.onmouseup = (e) => {
          el.classList.remove(CLS)
          document.onmousemove = document.onmouseup = null
          if (hasMove) {
            // 鼠标抬起时，如果之前发生过移动，则执行碰撞检测
            const { left, top, width, height } = area.style
            const areaTop = parseInt(top)
            const areaRight = parseInt(left) + parseInt(width)
            const areaBottom = parseInt(top) + parseInt(height)
            const areaLeft = parseInt(left)
            binding.value.selectIdxs.length = 0
            optionsXYWH.forEach((v, i) => {
              const optionTop = v.y
              const optionRight = v.x + v.w
              const optionBottom = v.y + v.h
              const optionLeft = v.x
              if (!(areaTop > optionBottom || areaRight < optionLeft || areaBottom < optionTop || areaLeft > optionRight)) {
                // 该指令的调用者可以监听到selectIdxs的变化
                let dom  = v.obj.querySelector('[batch-select-dataset]')
                binding.value.selectIdxs.push({
                  dataset: dom?.dataset,
                  content: dom?.value,
                  index: i
                })
              }
            })
          }
          // 恢复以下数据
          hasMove = false
          area.style.visibility = 'hidden'
          area.style.left = 0
          area.style.top = 0
          area.style.width = 0
          area.style.height = 0
          // 清除代码
          optionsXYWH = []
          return false
        }
      }
    }
  })
}
